package com.wink_172.activity

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.wink_172.commons.R
import com.wink_172.commons.databinding.ActivityControlBinding
import com.wink_172.library.activity.SmartActivity
import com.wink_172.library.adapter.CustomViewPagerAdapter
import com.wink_172.library.fragment.BaseFragment
import com.wink_172.library.model.Constants
import com.wink_172.library.utils.CommonUtils.getNumTypeface
import com.wink_172.library.utils.CommonUtils.getTypeface2
import com.wink_172.library.utils.CommonUtils.getTypeface3
import com.wink_172.library.utils.DialogUtils
import com.wink_172.library.utils.DisplayUtil
import com.wink_172.library.utils.ImageUtil
import com.wink_172.library.view.*
import org.xutils.common.Callback
import org.xutils.http.RequestParams
import org.xutils.image.ImageOptions
import org.xutils.x
import java.io.File
import java.security.AccessController.getContext
import java.util.*
import kotlin.collections.ArrayList


/**
 * 基本控件使用 展示
 */
class ControlActivity : SmartActivity() {
    lateinit var binding: ActivityControlBinding

    companion object {
        @JvmStatic
        fun startActivity(context: Context, vararg args: Any?) {
            val intent = Intent(context, ControlActivity::class.java)

            //intent.putExtra(Constants.PARAM_DATA1, (String) args[0]);
            context.startActivity(intent)
        }
    }
     var pop_view: View? = null
     var dialog: Dialog? = null
     val titles: MutableList<String> = ArrayList()
     var customViewPagerAdapter: CustomViewPagerAdapter? = null
     val fragments: MutableList<BaseFragment> = ArrayList()
    private var tabLayoutMediator: TabLayoutMediator? = null

    val location0 = IntArray(2)
    val location1 = IntArray(2)
    val location2 = IntArray(2)
    val location3 = IntArray(2)
    val location4 = IntArray(2)
    val location5 = IntArray(2)

    var x0 = 0
    var x1 = 0
    var x2 = 0
    var x3 = 0
    var x4 = 0
    var x5 = 0


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_control)

        setStatusBarLightMode()
        initView()

        init()


    }

    /**
     * 文字上下滚动
     * */
    fun initScrollText() {
        var titleList: MutableList<String> = ArrayList()
        titleList.add("hello01")
        titleList.add("hello02")
        titleList.add("hello03")
        titleList.add("hello04")



        binding!!.scrollTextView.setTextList(titleList!!)
        binding!!.scrollTextView.setText(12f, 0, Color.BLACK) //设置属性
        binding!!.scrollTextView.setTextStillTime(3000) //设置停留时长间隔
        binding!!.scrollTextView.setAnimTime(200, 250) //设置进入和退出的时间间隔


//        binding!!.scrollTextView.setOnItemClickListener(VerticalTextview.OnItemClickListener { position ->
//            DanceLibraryActivity.startActivity(activity, 0, 1)
//        })

        binding!!.scrollTextView.startAutoScroll()

//        binding!!.scrollTextView.setRunning(false)
//        binding!!.scrollTextView.stopAutoScroll()
    }



    private fun init() {


        binding!!.container3.setBackgroundColor(resources.getColor(R.color.color_pan1))
        binding!!.container3.invalidate()

    binding!!.customCircle.onlyUpdate(2*120f)

        initScrollText()

        x.task().postDelayed(Runnable {
            binding!!.point0.getLocationInWindow(location0)
            binding!!.point1.getLocationInWindow(location1)
            binding!!.point2.getLocationInWindow(location2)
            binding!!.point3.getLocationInWindow(location3)
            binding!!.point4.getLocationInWindow(location4)
            binding!!.point5.getLocationInWindow(location5)

            x0 = location0[0]
            x1 = location1[0]//binding!!.point1.x.toInt()
            x2 = location2[0]
            x3 = location3[0]
            x4 = location4[0]
            x5 = location5[0]

            val iv_triangle_lp = binding!!.progress.layoutParams as RelativeLayout.LayoutParams
            iv_triangle_lp.width = x5 - x0
            iv_triangle_lp.leftMargin = binding!!.point1.x.toInt() + DisplayUtil.dp2px(
                x.app(),
                10f
            ) - DisplayUtil.dp2px(x.app(), 2f)//起始值往右偏移一个点的距离10f   再往左偏移2dp意思一下


            showLevel(3, 6000)
        }, 300)

        binding!!.tabBtn5.isActivated = true
        (binding!!.circleTimeView as CircleTimeView).startCountDown(200)

        (binding!!.countDownView as CountTimeView).init("" + System.currentTimeMillis())
        (binding!!.countDownView as CountTimeView).saveCurrentTime();
        (binding!!.countDownView as CountTimeView).startCutDownTime(15 * 1000)
        binding!!.pointHint1.setTypeface(getTypeface2())
        binding!!.pointHint2.setTypeface(getTypeface2())
        binding!!.pointHint3.setTypeface(getTypeface2())
        binding!!.pointHint4.setTypeface(getTypeface2())
        binding!!.pointHint5.setTypeface(getTypeface3())


        titles.add("")
        titles.add("")
        val fragment01 = BaseFragment()
        val fragment02 = BaseFragment()
        fragments.add(fragment01)
        fragments.add(fragment02)
        customViewPagerAdapter = CustomViewPagerAdapter(this, titles, fragments)
        binding!!.viewPager.adapter = customViewPagerAdapter
        binding!!.viewPager.isUserInputEnabled = false //禁止滑动
        binding!!.viewPager.offscreenPageLimit = 2
        updateTitle("金属价格", "价值排行")

        (binding!!.circleTimeView as CircleTimeView).setCallback(object : CircleTimeView.ICallback {
            override fun onSendEvent(event: Int, vararg args: Any) {
                if (event == Constants.EVENT_02) {

                }
            }
        })


//        binding.progressLoading.background=x.app().resources.getDrawable(R.drawable.shap_black_4dp)
        (binding!!.progressLoading as ProgressLoading).tv_message.setText("上传中...")

        val options1 = ImageOptions.Builder()
            .setUseMemCache(true)
            .setFadeIn(true)
//            .setImageScaleType(ImageView.ScaleType.CENTER_CROP) //适配显示   //MATRIX可以   --FIT_START  FIT_CENTER  FIT_END  FIT_CENTER不可以
            .build()

        x.image().bind(
            binding?.pictureView,
            "https://static.hongbaodada.com/zao/dynamic_compress_size_CUQBScreenshot_2022-02-07-15-29-20-585_com.miui.home.jpg",
            options1
        )
//        downLoadFile(
//            "https://static.hongbaodada.com/zao/dynamic_compress_size_CUQBScreenshot_2022-02-07-15-29-20-585_com.miui.home.jpg",
//            Constants.savePath + "test.jpg"
//        )
    }

     fun showLevel(userLevel: Int, amount: Int) {
        binding!!.progress.visibility = View.VISIBLE

        Log.e(TAG, "showLevel: ====>>" + userLevel + "   amount:" + amount)

        val all_l = x5 - x0//进度条总长度
        val point_w = 0//+DisplayUtil.dp2px(x.app(), 6f)
        var add_amount = 0//达到该等级后超出的金额
        var add_process = 0//达到该等级后超出的process

        val process_point1 =
            (((x1 - x0 + point_w).toDouble() / all_l) * 100).toInt()  //0-300占总长度的进度15   加起来正好98
        val process_point2 =
            (((x2 - x1 + point_w).toDouble() / all_l) * 100).toInt() //300-2000占总长度的进度18
        val process_point3 =
            (((x3 - x2 + point_w).toDouble() / all_l) * 100).toInt() //20000-100000占总长度的进度21
        val process_point4 =
            (((x4 - x3 + point_w).toDouble() / all_l) * 100).toInt() //100000-600000占总长度的进度22
        val process_point5 =
            (((x5 - x4 + point_w).toDouble() / all_l) * 100).toInt() //600000-800000占总长度的进度22

        Log.e(
            TAG,
            "showLevel: ====02：  all_l：" + all_l + "   process_point1:" + process_point1 + "   process_point2:" + process_point2 +
                    "   process_point3：" + process_point3 + "    process_point4:" + process_point4 + "   process_point5:" + process_point5
        )

        when (userLevel) {
            0 -> {
                binding!!.point0.isActivated = true
                add_amount = amount - 0
                add_process = (add_amount.toDouble() * process_point1 / (300 - 0)).toInt()
//              binding!!.vipContainer.background=resources.getDrawable(R.mipmap.ic_bg0)
//              Log.e(TAG, "add_process: ====>>" + add_process)
                binding!!.progress.progress = 0 + add_process
                Log.e(
                    TAG,
                    "showLevel: ====>>03   :  add_amount:" + add_amount + "   add_process:" + add_process
                )
            }
            1 -> {
                binding!!.point0.isActivated = true
                binding!!.point1.isActivated = true
                add_amount = amount - 300
                add_process = (add_amount.toDouble() * process_point2 / (1000 - 300)).toInt()
                Log.e(
                    TAG,
                    "showLevel: ====>>03   :  add_amount:" + add_amount + "   add_process:" + add_process
                )
                binding!!.progress.progress = process_point1 + add_process
            }
            2 -> {
                binding!!.point0.isActivated = true
                binding!!.point1.isActivated = true
                binding!!.point2.isActivated = true
                add_amount = amount - 1000
                add_process = (add_amount.toDouble() * process_point3 / (5000 - 1000)).toInt()
                binding!!.progress.progress = process_point1 + process_point2 + add_process
                Log.e(
                    TAG,
                    "showLevel: ====>>03   :  add_amount:" + add_amount + "   add_process:" + add_process
                )
            }
            3 -> {
                binding!!.point0.isActivated = true
                binding!!.point1.isActivated = true
                binding!!.point2.isActivated = true
                binding!!.point3.isActivated = true
                add_amount = amount - 5000
                add_process = (add_amount.toDouble() * process_point4 / (10000 - 5000)).toInt()
                binding!!.progress.progress =
                    process_point1 + process_point2 + process_point3 + add_process
                Log.e(
                    TAG,
                    "showLevel: ====>>03   :  add_amount:" + add_amount + "   add_process:" + add_process
                )
                Log.e(
                    TAG,
                    "showLevel add_process: ====>>" + binding!!.progress.progress + "    :" + process_point3 + "    :" + add_process
                )
            }
            4 -> {
                binding!!.point0.isActivated = true
                binding!!.point1.isActivated = true
                binding!!.point2.isActivated = true
                binding!!.point3.isActivated = true
                binding!!.point4.isActivated = true

                add_amount = amount - 10000
                add_process = (add_amount.toDouble() * process_point5 / (50000 - 10000)).toInt()
                binding!!.progress.progress =
                    process_point1 + process_point2 + process_point3 + process_point4 + add_process
                Log.e(
                    TAG,
                    "showLevel add_process: ====>>" + binding!!.progress.progress + "    :" + process_point3 + "    :" + add_process
                )
            }
            5 -> {
                binding!!.point0.isActivated = true
                binding!!.point1.isActivated = true
                binding!!.point2.isActivated = true
                binding!!.point3.isActivated = true
                binding!!.point4.isActivated = true
                binding!!.point5.isActivated = true

                add_amount = amount - 50000
                binding!!.progress.progress = 100
//                binding!!.vipContainer.background=resources.getDrawable(R.mipmap.ic_bg5)
            }
            else -> {
            }
        }

        if (pop_view != null) {
            binding!!.vipContainer.removeView(pop_view)
            pop_view = null
        }

        val lp = RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        pop_view = LayoutInflater.from(activity!!).inflate(R.layout.item_view136, null)
        val hint_view = pop_view!!.findViewById<TextView>(R.id.hint_view)
        hint_view.setText("" + amount)
        lp.leftMargin =
            ((binding!!.progress.progress.toDouble() / 100) * all_l).toInt() + DisplayUtil.dp2px(
                x.app(),
                6f
            )
        lp.bottomMargin = DisplayUtil.dp2px(x.app(), 27.5f)
        lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)

        binding!!.vipContainer.addView(pop_view, 0, lp)
    }


    private val TAG = "ControlActivity"

    /**
     * //将图片的长和宽缩小味原来的1/2
     */
    fun getBitmapOption(inSampleSize: Int): BitmapFactory.Options? {
        System.gc()
        val options = BitmapFactory.Options()
        options.inPurgeable = true
        options.inSampleSize = inSampleSize
        return options
    }


    /**
     * 下载图片
     * */
    fun downLoadFile(web_url: String?, save_path: String) {

        val params = RequestParams(web_url)
        // 为RequestParams设置文件下载后的保存路径
        params.saveFilePath = save_path
        Log.e(TAG, "downLoadFile: ====>>" + save_path)

        // 下载完成后自动为文件命名
//        params.setAutoRename(true);
        x.http().get(params, object : Callback.ProgressCallback<File?> {
            override fun onSuccess(result: File?) {
                val bitmap =
                    BitmapFactory.decodeFile(
                        save_path,
                        getBitmapOption(2)
                    );
                (binding?.pictureView as RoundImageViewXutils).setImageBitmap(bitmap)

                val bit2: Bitmap = ImageUtil.centerSquareScaleBitmap(bitmap, 500)
                val bit3: Bitmap = ImageUtil.roundBitmapByShader(bit2, 500, 500, 20)
//                (binding?.pictureView2 as ImageView).setImageBitmap(bit3)
            }

            override fun onError(ex: Throwable, isOnCallback: Boolean) {
            }

            override fun onCancelled(cex: Callback.CancelledException) {}
            override fun onFinished() {
//                Log.e(TAG, "onFinished: ====>>")

            }

            override fun onWaiting() {}
            override fun onStarted() {}
            override fun onLoading(total: Long, current: Long, isDownloading: Boolean) {
                // 当前的下载进度和文件总大小

            }
        })
    }//获取调用的函数堆栈信息

    private fun initView() {
//        (binding!!.actionBar as KotlinActionBarView).updateAllContent(R.mipmap.icon_nav_arrow, "控件展示", "");
//        (binding!!.actionBar as KotlinActionBarView).setCallback (object : KotlinActionBarView.ICallback {
//            override fun onSendEvent(event: Int, content: String?) {
//                if (event == KotlinActionBarView.LEFT_BTN) {
//                    finish()
//                }
//            }
//        })

        binding!!.progress.setOnClickListener(this)
        binding!!.pictureView.setOnClickListener(this)
        binding!!.countDownView.setOnClickListener(this)
        binding!!.tabBtn5.setOnClickListener(this)
        binding!!.tabBtn6.setOnClickListener(this)
        binding!!.tabBtn1.setOnClickListener(this)
        binding!!.tabBtn2.setOnClickListener(this)
        binding!!.btnHome.setOnClickListener(this)
        binding!!.btnMine.setOnClickListener(this)
        binding!!.btnSel1.setOnClickListener(this)
        binding!!.btnSelMetal.setOnClickListener(this)
        binding!!.dialogButton1.setOnClickListener(this)
        binding!!.dialogButton2.setOnClickListener(this)





    }


    override fun onClick(v: View) {
        super.onClick(v)
        var active = false
        when (v.id) {
            R.id.dialog_button1 -> showCommonDialog(R.style.dialog, true)
            R.id.dialog_button2 -> showCommonDialog(R.style.CustomProgressDialog, false)
            R.id.btn_sel1 -> {
                active = binding!!.btnSel1.isActivated
                binding!!.btnSel1.isActivated = !active
            }
            R.id.tab_btn1 -> {
                binding!!.tabBtn1.isActivated = true
                binding!!.tabBtn2.isActivated = false
            }
            R.id.tab_btn2 -> {
                binding!!.tabBtn1.isActivated = false
                binding!!.tabBtn2.isActivated = true
            }
            R.id.count_down_view -> {
                (binding!!.countDownView as CountTimeView).stopCutDownTime()
            }
        }
    }


    fun updateTitle(left: String, right: String) {
        if (!TextUtils.isEmpty(left)) {
            titles[0] = left
        }
        if (!TextUtils.isEmpty(right)) {
            titles[1] = right
        }
        tabLayoutMediator = TabLayoutMediator(
            binding!!.tabLayout1,
            binding!!.viewPager
        ) { tab, position -> setTabTextView(tab, position) }
        tabLayoutMediator!!.attach()
        binding!!.viewPager.registerOnPageChangeCallback(object : OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                updateTabTextView(position)
            }
        })
    }

    /**
     * 字体加粗变颜色
     *
     * @param tab
     * @param
     */
    fun setTabTextView(tab: TabLayout.Tab, position: Int) {
        tab.setCustomView(R.layout.tab_layout_text)
        val view = tab.customView
        val textView: UnderlineTextView = view!!.findViewById(R.id.text1)
        textView.text = titles[position]
        //        textView.updateLine(DisplayUtil.dp2px(this, 2));
    }

    fun updateTabTextView(pos_select: Int) {
        for (i in 0 until binding!!.tabLayout1.tabCount) {
            val tab = binding!!.tabLayout1.getTabAt(i)
            val view = tab!!.customView
            val textView: UnderlineTextView = view!!.findViewById(R.id.text1)
            if (pos_select == i) {
                textView.updateLine(DisplayUtil.dp2px(this, 4f))
                textView.isActivated = true
            } else {
                textView.updateLine(0)
                textView.isActivated = false
            }
        }
    }

    /**
     * 确认弹窗
     */
    fun showCommonDialog(styleId: Int, full_screen: Boolean) {
        dialog = Dialog(this, styleId)
        dialog!!.setContentView(R.layout.dialog_common)
        dialog!!.show()

//      设置宽度全屏，要设置在show的后面
        if (full_screen) {
            val layoutParams = dialog!!.window!!.attributes
            layoutParams.gravity = Gravity.CENTER
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
            layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT
            dialog!!.window!!.decorView.setPadding(0, 0, 0, 0)
            dialog!!.window!!.attributes = layoutParams
        }
        val title_view = dialog!!.findViewById<TextView>(R.id.title_view)
        val btn_right = dialog!!.findViewById<ImageView>(R.id.btn_right)
        val content_view = dialog!!.findViewById<TextView>(R.id.content_view)
        val btn_cancel = dialog!!.findViewById<TextView>(R.id.btn_cancel)
        val btn_confirm = dialog!!.findViewById<TextView>(R.id.btn_confirm)
        title_view.text = ""
        content_view.text = "确定要删除吗?"
        btn_right.setOnClickListener { hideConfirmDialog() }
        btn_cancel.setOnClickListener { hideConfirmDialog() }
        btn_confirm.setOnClickListener { hideConfirmDialog() }
    }

    fun hideConfirmDialog() {
        if (dialog != null) {
            dialog!!.dismiss()
            dialog = null
        }
    }


}